package com.leigang.boot.redis.springbootredis.controller;

import com.leigang.boot.redis.springbootredis.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author leigang
 * @version 1.0
 * @date 2022/7/10 21:16
 **/
@RestController
@Slf4j
public class RessionController {
    private final StringRedisTemplate redisTemplate;
    private final static String STOCK = "stock";

    public RessionController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    public void setUp() {
        log.info("初始化50个库存");
        redisTemplate.opsForValue().set(STOCK, "50");
    }

    /**
     * 获取锁
     *
     * @return 库存数
     */
    private int getLock() {
        String s = redisTemplate.opsForValue().get(STOCK);
        log.info("库存数：{}", s);
        return Integer.parseInt(Objects.nonNull(s) ? s : "0");
    }

    /**
     * 秒杀流程
     */
    @GetMapping("/sec-kill")
    public Map<String, Object> secKill() {
        String stockKey = "product_1001";
        try {
            // 1.不存在key则设置，存在直接返回
            Boolean result = redisTemplate.opsForValue().setIfAbsent(stockKey, "1");
            if (Objects.isNull(result) || !result) {
                return new HashMap<>();
            }
            // ②.设置过期时间
            redisTemplate.expire(stockKey, 10, TimeUnit.SECONDS);
            int stock = getLock();
            if (stock > 0) {
                int realStock = stock - 1;
                redisTemplate.opsForValue().set(STOCK, String.valueOf(realStock));
                log.info("扣减成功，剩余库存：{}", realStock);
                return ResponseUtils.success("获取成功");
            } else {
                log.info("扣减失败，库存不足");
                return ResponseUtils.success("扣减失败，库存不足");
            }
        } finally {
            // ③.删除key（释放锁）
            redisTemplate.delete(stockKey);
        }
    }
}
